<template>
    <div class="scroll-top" @click="returnTop">
        <div class="icon-container">
            <div @click="updateIsPlay">
                <img-icon name="music" size="1.5rem" class="isClick" />
            </div>
            <div v-if="isPlay" @click="updateIsPlay">
                <img-icon name="pause" size="1.5rem" class="isClick" />
            </div>
            <div v-else @click="updateIsPlay">
                <img-icon name="play" size="1.5rem" class="isClick" />
            </div>
            <div @click="scrollToTop" class="top-box">
                <img-icon name="top" size="1.5rem" class="isClick" />
            </div>
            <div @click="scrollToTop" class="progress-text">
                {{ scrolledPercentage.toFixed(0) }}%
            </div>
        </div>
    </div>
</template>
<script>
import ImgIcon from "./ImgIcon.vue";

export default {
    name: "scroll-top",
    components: { ImgIcon },
    data() {
        return {
            isPlay: true,
            scrolledPercentage: 0, // 初始滚动百分比为0
        };
    },
    mounted() {
        window.addEventListener("scroll", this.updateProgressBar); // 监听滚动事件
    },
    destroyed() {
        window.removeEventListener("scroll", this.updateProgressBar); // 移除滚动事件监听
    },
    methods: {
        updateProgressBar() {
            const scrollHeight = document.documentElement.scrollHeight; // 整个页面的高度
            const scrollTop = window.scrollY || window.pageYOffset; // 当前滚动位置
            const windowHeight = window.innerHeight; // 可视窗口的高度

            this.scrolledPercentage =
                (scrollTop / (scrollHeight - windowHeight)) * 100; // 计算滚动百分比
        },
        returnTop() {
            document.documentElement.scrollTop = document.body.scrollTop = 0;
        },
        scrollToTop() {
            window.scrollTo({ top: 0, behavior: "smooth" }); // 平滑滚动到页面顶部
        },
        updateIsPlay() {
            this.isPlay = !this.isPlay;
        },
    },
};
</script>

<style lang="scss" scoped>
@use "../assets/css/scroll-top.scss";
</style>
